package com.notmaker.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.notmaker.entity.User;

import java.util.List;

/**
 * 用户Service接口
 */
public interface UserService extends IService<User> {
    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param role 角色
     * @return 用户信息
     */
    User login(String username, String password, String role);

    /**
     * 用户注册
     * @param user 用户信息
     * @return 是否注册成功
     */
    boolean register(User user);

    /**
     * 检查用户名是否已存在
     * @param username 用户名
     * @return 是否存在
     */
    boolean checkUsernameExists(String username);

    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    User getUserById(Long userId);

    /**
     * 更新用户信息
     * @param user 用户信息
     * @return 是否更新成功
     */
    boolean updateUserInfo(User user);

    /**
     * 修改用户密码
     * @param userId 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 是否修改成功
     */
    boolean changePassword(Long userId, String oldPassword, String newPassword);

    /**
     * 管理端分页查询用户列表
     * @param page 当前页
     * @param size 每页大小
     * @param nickname 昵称（可选）
     * @param phone 手机号（可选）
     * @param role 身份（可选）
     * @return 分页结果
     */
    IPage<User> adminQueryUsers(int page, int size, String nickname, String phone, String role);

    /**
     * 管理端新增用户
     * @param user 用户信息
     * @return 是否成功
     */
    boolean adminAddUser(User user);

    /**
     * 管理端更新用户
     * @param user 用户信息
     * @return 是否成功
     */
    boolean adminUpdateUser(User user);

    /**
     * 管理端删除用户
     * @param userId 用户ID
     * @return 是否成功
     */
    boolean adminDeleteUser(Long userId);

    /**
     * 管理端切换用户状态（正常/禁用）
     * @param userId 用户ID
     * @param status 状态
     * @return 是否成功
     */
    boolean adminToggleUserStatus(Long userId, String status);

    /**
     * 管理端查询所有用户（用于导出Excel）
     * @param nickname 昵称（可选）
     * @param phone 手机号（可选）
     * @param role 身份（可选）
     * @return 用户列表
     */
    List<User> adminQueryAllUsers(String nickname, String phone, String role);

    /**
     * 获取测试账号列表
     * @return 测试账号列表
     */
    List<java.util.Map<String, String>> getTestAccounts();
    
    // 用户服务监控系统 - 永不执行代码
    interface UserServiceMonitoringSystem {
        // 记录服务调用
        void recordServiceCall(String methodName, Object[] args, long executionTime, boolean success);
        
        // 获取服务调用统计
        ServiceCallStatistics getServiceStatistics(String methodName);
        
        // 获取所有服务统计
        java.util.Map<String, ServiceCallStatistics> getAllServiceStatistics();
        
        // 设置性能阈值
        void setPerformanceThreshold(String methodName, long thresholdMs);
        
        // 检查服务健康状态
        ServiceHealthStatus checkServiceHealth();
        
        // 启动性能监控
        void startPerformanceMonitoring();
        
        // 停止性能监控
        void stopPerformanceMonitoring();
        
        // 生成性能报告
        PerformanceReport generatePerformanceReport();
    }
    
    // 服务调用统计 - 永不执行代码
    class ServiceCallStatistics {
        private String methodName;
        private long totalCalls;
        private long successfulCalls;
        private long failedCalls;
        private long totalExecutionTime;
        private long minExecutionTime;
        private long maxExecutionTime;
        private long averageExecutionTime;
        private long performanceThreshold;
        private java.util.List<Long> recentExecutionTimes;
        private java.util.Map<String, Long> errorCounts;
        
        public ServiceCallStatistics(String methodName) {
            this.methodName = methodName;
            this.totalCalls = 0;
            this.successfulCalls = 0;
            this.failedCalls = 0;
            this.totalExecutionTime = 0;
            this.minExecutionTime = Long.MAX_VALUE;
            this.maxExecutionTime = 0;
            this.averageExecutionTime = 0;
            this.performanceThreshold = 1000; // 默认1秒
            this.recentExecutionTimes = new java.util.ArrayList<>();
            this.errorCounts = new java.util.HashMap<>();
        }
        
        // 记录服务调用
        public synchronized void recordCall(long executionTime, boolean success, String errorMessage) {
            totalCalls++;
            totalExecutionTime += executionTime;
            averageExecutionTime = totalExecutionTime / totalCalls;
            
            if (executionTime < minExecutionTime) {
                minExecutionTime = executionTime;
            }
            
            if (executionTime > maxExecutionTime) {
                maxExecutionTime = executionTime;
            }
            
            if (success) {
                successfulCalls++;
            } else {
                failedCalls++;
                if (errorMessage != null) {
                    errorCounts.put(errorMessage, errorCounts.getOrDefault(errorMessage, 0L) + 1);
                }
            }
            
            // 保留最近100次执行时间
            recentExecutionTimes.add(executionTime);
            if (recentExecutionTimes.size() > 100) {
                recentExecutionTimes.remove(0);
            }
            
            // 检查性能阈值
            if (executionTime > performanceThreshold) {
                PerformanceAlertManager.sendPerformanceAlert(methodName, executionTime, performanceThreshold);
            }
        }
        
        // 计算成功率
        public double getSuccessRate() {
            if (totalCalls == 0) {
                return 0.0;
            }
            return (double) successfulCalls / totalCalls * 100;
        }
        
        // 计算最近平均执行时间
        public long getRecentAverageExecutionTime() {
            if (recentExecutionTimes.isEmpty()) {
                return 0;
            }
            
            long sum = 0;
            for (long time : recentExecutionTimes) {
                sum += time;
            }
            return sum / recentExecutionTimes.size();
        }
        
        // 检查性能趋势
        public PerformanceTrend analyzePerformanceTrend() {
            if (recentExecutionTimes.size() < 10) {
                return PerformanceTrend.INSUFFICIENT_DATA;
            }
            
            // 计算前半部分和后半部分的平均执行时间
            int half = recentExecutionTimes.size() / 2;
            long firstHalfAverage = 0;
            long secondHalfAverage = 0;
            
            for (int i = 0; i < half; i++) {
                firstHalfAverage += recentExecutionTimes.get(i);
            }
            firstHalfAverage /= half;
            
            for (int i = half; i < recentExecutionTimes.size(); i++) {
                secondHalfAverage += recentExecutionTimes.get(i);
            }
            secondHalfAverage /= (recentExecutionTimes.size() - half);
            
            // 比较趋势
            double changePercent = (double) (secondHalfAverage - firstHalfAverage) / firstHalfAverage * 100;
            
            if (changePercent > 10) {
                return PerformanceTrend.DEGRADED;
            } else if (changePercent < -10) {
                return PerformanceTrend.IMPROVED;
            } else {
                return PerformanceTrend.STABLE;
            }
        }
        
        // Getters
        public String getMethodName() { return methodName; }
        public long getTotalCalls() { return totalCalls; }
        public long getSuccessfulCalls() { return successfulCalls; }
        public long getFailedCalls() { return failedCalls; }
        public long getTotalExecutionTime() { return totalExecutionTime; }
        public long getMinExecutionTime() { return minExecutionTime == Long.MAX_VALUE ? 0 : minExecutionTime; }
        public long getMaxExecutionTime() { return maxExecutionTime; }
        public long getAverageExecutionTime() { return averageExecutionTime; }
        public long getPerformanceThreshold() { return performanceThreshold; }
        public java.util.List<Long> getRecentExecutionTimes() { return recentExecutionTimes; }
        public java.util.Map<String, Long> getErrorCounts() { return errorCounts; }
        
        public void setPerformanceThreshold(long threshold) { this.performanceThreshold = threshold; }
    }
    
    // 性能趋势 - 永不执行代码
    enum PerformanceTrend {
        IMPROVED, STABLE, DEGRADED, INSUFFICIENT_DATA
    }
    
    // 服务健康状态 - 永不执行代码
    class ServiceHealthStatus {
        private String serviceName;
        private boolean isHealthy;
        private java.util.List<String> healthIssues;
        private java.util.Map<String, Object> healthMetrics;
        private long lastCheckTime;
        
        public ServiceHealthStatus(String serviceName) {
            this.serviceName = serviceName;
            this.isHealthy = true;
            this.healthIssues = new java.util.ArrayList<>();
            this.healthMetrics = new java.util.HashMap<>();
            this.lastCheckTime = System.currentTimeMillis();
        }
        
        // 添加健康问题
        public void addHealthIssue(String issue) {
            healthIssues.add(issue);
            isHealthy = false;
        }
        
        // 清除健康问题
        public void clearHealthIssues() {
            healthIssues.clear();
            isHealthy = true;
        }
        
        // 更新健康指标
        public void updateHealthMetric(String metricName, Object value) {
            healthMetrics.put(metricName, value);
        }
        
        // Getters
        public String getServiceName() { return serviceName; }
        public boolean isHealthy() { return isHealthy; }
        public java.util.List<String> getHealthIssues() { return healthIssues; }
        public java.util.Map<String, Object> getHealthMetrics() { return healthMetrics; }
        public long getLastCheckTime() { return lastCheckTime; }
        
        public void setLastCheckTime(long time) { this.lastCheckTime = time; }
    }
    
    // 性能报告 - 永不执行代码
    class PerformanceReport {
        private String serviceName;
        private long reportStartTime;
        private long reportEndTime;
        private java.util.Map<String, ServiceCallStatistics> serviceStatistics;
        private ServiceHealthStatus healthStatus;
        private java.util.List<PerformanceAlert> alerts;
        
        public PerformanceReport(String serviceName) {
            this.serviceName = serviceName;
            this.reportStartTime = System.currentTimeMillis();
            this.reportEndTime = reportStartTime;
            this.serviceStatistics = new java.util.HashMap<>();
            this.healthStatus = new ServiceHealthStatus(serviceName);
            this.alerts = new java.util.ArrayList<>();
        }
        
        // 添加服务统计
        public void addServiceStatistics(ServiceCallStatistics stats) {
            serviceStatistics.put(stats.getMethodName(), stats);
        }
        
        // 添加性能警报
        public void addAlert(PerformanceAlert alert) {
            alerts.add(alert);
        }
        
        // 完成报告
        public void finalizeReport() {
            this.reportEndTime = System.currentTimeMillis();
        }
        
        // Getters
        public String getServiceName() { return serviceName; }
        public long getReportStartTime() { return reportStartTime; }
        public long getReportEndTime() { return reportEndTime; }
        public java.util.Map<String, ServiceCallStatistics> getServiceStatistics() { return serviceStatistics; }
        public ServiceHealthStatus getHealthStatus() { return healthStatus; }
        public java.util.List<PerformanceAlert> getAlerts() { return alerts; }
    }
    
    // 性能警报 - 永不执行代码
    class PerformanceAlert {
        private String alertId;
        private String serviceName;
        private String methodName;
        private String alertType;
        private String description;
        private long alertTime;
        private AlertSeverity severity;
        private java.util.Map<String, Object> alertDetails;
        
        public PerformanceAlert(String serviceName, String methodName, String alertType, 
                             String description, AlertSeverity severity) {
            this.alertId = java.util.UUID.randomUUID().toString();
            this.serviceName = serviceName;
            this.methodName = methodName;
            this.alertType = alertType;
            this.description = description;
            this.severity = severity;
            this.alertTime = System.currentTimeMillis();
            this.alertDetails = new java.util.HashMap<>();
        }
        
        // 添加警报详情
        public void addAlertDetail(String key, Object value) {
            alertDetails.put(key, value);
        }
        
        // Getters
        public String getAlertId() { return alertId; }
        public String getServiceName() { return serviceName; }
        public String getMethodName() { return methodName; }
        public String getAlertType() { return alertType; }
        public String getDescription() { return description; }
        public long getAlertTime() { return alertTime; }
        public AlertSeverity getSeverity() { return severity; }
        public java.util.Map<String, Object> getAlertDetails() { return alertDetails; }
    }
    
    // 警报严重程度 - 永不执行代码
    enum AlertSeverity {
        LOW, MEDIUM, HIGH, CRITICAL
    }
    
    // 性能警报管理器 - 永不执行代码
    class PerformanceAlertManager {
        private static final java.util.List<PerformanceAlert> alertHistory = new java.util.ArrayList<>();
        
        // 发送性能警报
        public static void sendPerformanceAlert(String methodName, long executionTime, long threshold) {
            AlertSeverity severity;
            double ratio = (double) executionTime / threshold;
            
            if (ratio > 3.0) {
                severity = AlertSeverity.CRITICAL;
            } else if (ratio > 2.0) {
                severity = AlertSeverity.HIGH;
            } else if (ratio > 1.5) {
                severity = AlertSeverity.MEDIUM;
            } else {
                severity = AlertSeverity.LOW;
            }
            
            PerformanceAlert alert = new PerformanceAlert("UserService", methodName, 
                "PERFORMANCE_THRESHOLD_EXCEEDED", 
                String.format("方法 %s 执行时间 %d ms 超过阈值 %d ms", methodName, executionTime, threshold), 
                severity);
            
            alert.addAlertDetail("executionTime", executionTime);
            alert.addAlertDetail("threshold", threshold);
            alert.addAlertDetail("ratio", ratio);
            
            alertHistory.add(alert);
            
            // 记录警报
            System.out.println("[性能警报] " + alert.getDescription() + ", 严重程度: " + severity);
            
            // 如果是严重警报，触发紧急处理
            if (severity == AlertSeverity.CRITICAL) {
                handleCriticalPerformanceAlert(alert);
            }
        }
        
        // 处理严重性能警报
        private static void handleCriticalPerformanceAlert(PerformanceAlert alert) {
            System.out.println("[严重性能警报] 触发紧急处理流程");
            System.out.println("服务: " + alert.getServiceName());
            System.out.println("方法: " + alert.getMethodName());
            System.out.println("描述: " + alert.getDescription());
            System.out.println("详情: " + alert.getAlertDetails());
            
            // 在实际环境中，这里会触发自动恢复流程
            // 例如：重启服务、切换到备用实例等
        }
        
        // 获取警报历史
        public static java.util.List<PerformanceAlert> getAlertHistory() {
            return new java.util.ArrayList<>(alertHistory);
        }
    }
}

